<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-form-model-item label="用户姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="realname">
          <a-input placeholder="请输入用户姓名" v-model="model.realname" />
        </a-form-model-item>

        <a-form-model-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="phone" >
          <a-input placeholder="请输入手机号码" v-model="model.phone" />
        </a-form-model-item>

        <template v-if="title_ === '新增'">
          <a-form-model-item label="登录密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="password" has-feedback>
            <a-input type="password" placeholder="请输入登录密码" v-model="model.password" />
          </a-form-model-item>

          <a-form-model-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="confirmpassword" has-feedback>
            <a-input type="password" placeholder="请重新输入登录密码" v-model="model.confirmpassword" />
          </a-form-model-item>
        </template>

        <a-divider />

        <!--部门分配-->
        <a-form-model-item label="部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="selecteddeparts">
          <j-select-depart v-model="model.selecteddeparts" :multi="false" :backDepart="true" :treeOpera="true" ></j-select-depart>
        </a-form-model-item>

        <a-form-model-item label="角色权限" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="selectedroles">
          <j-multi-select-tag  v-model="model.selectedroles" :options="rolesOptions" placeholder="请选择组织权限"></j-multi-select-tag>
        </a-form-model-item>

        <a-form-model-item label="是否启用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status" >
          <j-switch v-model="model.status" ></j-switch>
        </a-form-model-item>

        <store-warehouse-auth ref="shopWarehouseRef" ></store-warehouse-auth>

      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import { addUser, editUser, duplicateCheck } from '@/api/api'
  import { getAction } from '@api/manage'
  import storeWarehouseAuth from './storeWarehouseAuth.vue'
  export default {
    name: 'UserModalForm',
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      orgCode: {
        type: String,
        default: ''
      },
      title_: {
        type: String,
        default: ''
      },
      rolesOptions: {
        type: Array,
        default: () => []
      },
    },
    components:{storeWarehouseAuth},
    data() {
      return {
        validatorRules: {
          password: [
            {
              required: true,
              pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{8,16}$/,
              message: '密码由8-16位数字、大小写字母组成!',
            },
            { validator: this.validateToNextPassword },
          ],
          confirmpassword: [
            { required: true, message: '请重新输入登录密码!' },
            { validator: this.compareToFirstPassword },
          ],
          realname: [{ required: true, message: '请输入用户名称!' }],
          phone: [{ required: true, message: '请输入手机号!' }, { validator: this.validateMobile }],
          selecteddeparts: [{ required: true, message: '请选择权限部门!' }],
          selectedroles: [{ required: true, message: '请选择权限部门!' }],
        },
        storeList:[],
        warehouseList:[],
        storeParam: {
          currentPage : 1,
          pageSize : 20,
          total : 0
        },
        warehouseParam: {
          currentPage : 1,
          pageSize : 20,
          total : 0
        },
        model: {
          id:'',
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/file/upload',
          userWithDepart: '/sys/user/userDepartList', // 引入为指定用户查看部门信息需要的url
          userId: '/sys/user/generateUserId', // 引入生成添加用户情况下的url
          syncUserByrealname: '/act/process/extActProcess/doSyncUserByrealname', //同步用户到工作流
          queryTenantList: '/sys/tenant/queryList',
          merchantOrgList: "/sys/role/list",
          storeList: "/oms/store/storeAuthAmazon/storePageList",
          queryStore: "/oms/store/user/getStoreByUserId",
          warehouseList: "/wms/warehouse/warehousePageList",
          queryWarehouse: "/wms/warehouse/user/getWarehouseByUserId",
        },
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      }
    },
    created () {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    mounted() {
    },
    methods: {
      add() {
        this.edit(this.modelDefault,"add")
      },
      edit(record,type) {
        this.model = Object.assign({}, record, {status: record.status === 1 ? 'Y' : 'N'})
        this.$refs.shopWarehouseRef.init(record?.id || null)
      },

      //提交数据
      submitForm() {
        const that = this
        // 触发表单验证
        this.$refs.form.validate((valid) => {
          if (valid) {
           that.confirmLoading = true
            let ids = that.$refs.shopWarehouseRef.getSelectedIds()
            let params = Object.assign({}, this.model, {status: this.model.status === 'Y' ? 1 : 2},ids);
            let obj;
            if (!this.model.id) {
              obj = addUser(params)
            } else {
              obj = editUser(params)
            }
            obj.then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          }
        })
      },
      validateToNextPassword(rule, value, callback) {
        if (value && this.model.confirmpassword && value !== this.model.confirmpassword) {
          callback('两次输入的密码不一样！')
        }
        if (value && this.model.confirmpassword) {
          this.$refs.form.validateField(['confirmpassword'])
        }
        callback()
      },
      compareToFirstPassword(rule, value, callback) {
        if (value && value !== this.model.password) {
          callback('两次输入的密码不一样！')
        } else {
          callback()
        }
      },
      validateMobile(rule, value, callback) {
        if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[25789]|7[0135678]|9[89])\d{8}$/).test(value)) {
          callback()
        } else {
          callback('手机号码格式不正确!')
        }
      },
      // validatePhone(rule, value, callback) {
      //   if (!value) {
      //     callback()
      //   } else {
      //     if (new RegExp(/^1[3-9][0-9]{9}$/).test(value)) {
      //       var params = {
      //         tableName: 'sys_user',
      //         fieldName: 'phone',
      //         fieldVal: value,
      //         dataId: this.model.id,
      //       }
      //       duplicateCheck(params).then((res) => {
      //         if (res.success) {
      //           callback()
      //         } else {
      //           callback('手机号已存在!')
      //         }
      //       })
      //     } else {
      //       callback('请输入正确格式的手机号码!')
      //     }
      //   }
      // },
      // validaterealname(rule, value, callback) {
      //   var params = {
      //     tableName: 'sys_user',
      //     fieldName: 'realname',
      //     fieldVal: value,
      //     dataId: this.model.id,
      //   }
      //   duplicateCheck(params).then((res) => {
      //     if (res.success) {
      //       callback()
      //     } else {
      //       callback('用户名已存在!')
      //     }
      //   })
      // },
    },
  }
</script>

<style scoped>
.avatar-uploader>.ant-upload {
  width: 104px;
  height: 104px;
}

.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}
.tag{
  border: 1px solid #1890FF;
  padding: 2px 10px;
  border-radius: 6px;
  color: #1890FF;
  margin-bottom: 4px;
  display: inline-block;
}
/deep/.ant-divider-horizontal{
  margin: 10px 0;
}
</style>